package org.database.generator.code;

import org.database.generator.code.utils.Configuration;
import org.database.generator.code.utils.FreemarkerUtil;
import org.database.generator.code.utils.IOUtils;
import org.database.generator.code.model.Table;

import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author liangsu
 * @version v1.0
 * @Description
 * @Date 2019/8/28 9:41
 * @since
 */
public class TableHtmlGenerator {
    private TableInspector tableInspector = new TableInspector();

    public static void main(String[] args) {
        TableHtmlGenerator generator = new TableHtmlGenerator();
//        generator.create("dmall_rdp_voucher", "D:\database\\dmall_rdp_voucher\\");
//        generator.create("dmall_rdp_requisition", "D:\\database\\dmall_rdp_requisition\\");
//        generator.create("dmall_rdp_sms", "D:\\database\\dmall_rdp_sms\\");
//        generator.create("dmall_inventory_adjust", "D:\\database\\dmall_inventory_adjust\\");
        generator.create("dmall_inventory_count_rta", "D:\\database\\dmall_inventory_count_rta\\");
    }

    /**
     * @param schema 表名
     */
    public void create(String schema, String rootPath){
        List<Table> tables = tableInspector.queryTables4Html(schema);
//        List<Table> tables = new ArrayList<>();
//        tables.add(tableInspector.queryTable("SYS_USER_GROUP"));

        tables.forEach(table -> {
            Map<String, Object> root = new HashMap<>();
            initRootMap(root);
            root.put("table", table);
            root.put("charset", "UTF-8");

            FreemarkerUtil freemarkerUtil = FreemarkerUtil.getInstance("/template");
            String tableHtml = freemarkerUtil.process(root, "table.html");

            File file = new File(rootPath + table.getTableName().toLowerCase() + ".html");
            IOUtils.wirteStringToFile(tableHtml, file);
        });
    }

    private void initRootMap(Map<String, Object> root){
        DateFormat df = new SimpleDateFormat("yyyy年MM月dd日 HH:mm");
        root.put("date", df.format(new Date()));

        // 作者
        String author = Configuration.get("cy.author");
        if(author == null || "".equals(author)){
            author = System.getenv().get("COMPUTERNAME");
        }
        root.put("author", author);
    }
}
